import axios from "axios";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import router from '@/router'
import {ElMessage} from 'element-plus'

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
})

//前置拦截
service.interceptors.request.use(config => {
    //1、进度条开始
    NProgress.start()

    //2、添加token信息
    if(store.getters.token){
        config.headers['satoken'] = store.getters.token
    }

    return config
},error => {
    return Promise.reject(error)
})

//后置拦截
service.interceptors.response.use(response => {
    //1、关闭进度条
    NProgress.done()

    const result = response.data
    if(result.code === 200){
        return result
    }else if(result.code === 401){
        store.dispatch('logout')
        router.push({
            path: '/login'
        })
    }else {
        ElMessage.error(result.message)
        return Promise.reject(new Error(result.message))
    }
},error => {
    //状态码非200的处理
    //1、关闭进度条
    NProgress.done()
    //2、提示报错信息
    let {status,data} = error.response
    ElMessage.error(data.message)

    return Promise.reject(error)
})

export default service
